package com.booktrading.controller;

import com.booktrading.model.Book;
import com.booktrading.model.User;
import com.booktrading.service.BookService;
import com.booktrading.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 我的书籍控制器
 */
@Controller
@RequestMapping("/book/my-books")
public class MyBooksController {

    @Autowired
    private BookService bookService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 我的书籍列表页面
     */
    @GetMapping
    public String myBooksPage(Model model) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        if (currentUser == null) {
            return "redirect:/login";
        }
        
        // 查询用户发布的所有书籍
        List<Book> books = bookService.getBooksBySeller(currentUser.getId());
        
        // 分类统计
        Map<String, Long> categoryStats = new HashMap<>();
        Map<Integer, Long> statusStats = new HashMap<>();
        
        for (Book book : books) {
            // 分类统计
            String category = book.getCategory();
            if (category != null && !category.isEmpty()) {
                categoryStats.put(category, categoryStats.getOrDefault(category, 0L) + 1);
            }
            
            // 状态统计（1在售，0下架）
            Integer status = book.getStatus();
            statusStats.put(status, statusStats.getOrDefault(status, 0L) + 1);
        }
        
        model.addAttribute("books", books);
        model.addAttribute("categoryStats", categoryStats);
        model.addAttribute("statusStats", statusStats);
        model.addAttribute("totalBooks", books.size());
        model.addAttribute("onSaleCount", statusStats.getOrDefault(1, 0L));
        model.addAttribute("offSaleCount", statusStats.getOrDefault(0, 0L));
        
        return "book/my-books";
    }
    
    /**
     * 下架书籍
     */
    @PostMapping("/remove/{id}")
    @ResponseBody
    public Map<String, Object> removeBook(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        // 获取书籍信息
        Book book = bookService.getBookById(id);
        if (book == null) {
            result.put("success", false);
            result.put("message", "书籍不存在");
            return result;
        }
        // 权限检查：只允许卖家删除自己的书籍
        if (!book.getSellerId().equals(currentUser.getId())) {
            result.put("success", false);
            result.put("message", "无权删除他人书籍");
            return result;
        }
        // 删除书籍
        boolean success = bookService.deleteBook(id);
        if (success) {
            result.put("success", true);
            result.put("message", "删除成功");
        } else {
            result.put("success", false);
            result.put("message", "删除失败");
        }
        return result;
    }
    
    /**
     * 重新上架书籍
     */
    @PostMapping("/relist/{id}")
    @ResponseBody
    public Map<String, Object> relistBook(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        // 获取书籍信息
        Book book = bookService.getBookById(id);
        
        if (book == null) {
            result.put("success", false);
            result.put("message", "书籍不存在");
            return result;
        }
        
        // 权限检查：只允许卖家上架自己的书籍
        if (!book.getSellerId().equals(currentUser.getId())) {
            result.put("success", false);
            result.put("message", "无权上架他人书籍");
            return result;
        }
        
        // 重新上架书籍
        boolean success = bookService.updateBookStatus(id, 1);
        
        if (success) {
            result.put("success", true);
            result.put("message", "上架成功");
        } else {
            result.put("success", false);
            result.put("message", "上架失败");
        }
        
        return result;
    }
    
    /**
     * 删除书籍
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteBook(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User currentUser = userService.getUserByUsername(username);
        
        // 获取书籍信息
        Book book = bookService.getBookById(id);
        
        if (book == null) {
            result.put("success", false);
            result.put("message", "书籍不存在");
            return result;
        }
        
        // 权限检查：只允许卖家删除自己的书籍
        if (!book.getSellerId().equals(currentUser.getId())) {
            result.put("success", false);
            result.put("message", "无权删除他人书籍");
            return result;
        }
        
        // 删除书籍
        boolean success = bookService.deleteBook(id);
        
        if (success) {
            result.put("success", true);
            result.put("message", "删除成功");
        } else {
            result.put("success", false);
            result.put("message", "删除失败");
        }
        
        return result;
    }
} 